package com.hongxun.design.jungong.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.jungong.adapter.Adapter_OldBj;
import com.hongxun.design.jungong.utils.IntentUtil;
import com.hongxun.design.jungong.utils.jxlUtil;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.sqlite.bean.OldBj;
import com.hongxun.design.sqlite.dao.OldBjDao;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.pop.android.common.util.ToastUtils;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.hongxun.design.R.id.design_continue_button;

public class OldBjActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private HeadSecondControlPanel headsecond_layout;
    private SwipeRefreshListView refreshListView;
    private ArrayList<OldBj> detailList = new ArrayList<>();
    private Adapter_OldBj adapter;
    private TextView sync_button;
    private int startNum = 0;
    private int addNum = MyApp.addNum;
    OldBjDao dao;
    private LinearLayout layoutMainView;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 3:
                    String valueOf1 = String.valueOf(msg.obj);
                    if (valueOf1.endsWith("2")) {//手动选取
                        Intent intent = IntentUtil.showFileChooser(1);
                        startActivityForResult(intent, 2);
                    } else if (valueOf1.endsWith("1")) {//QQ
                        if (fileList_QQ.isEmpty()) {
                            ToastShow.showShort(OldBjActivity.this, "没有自动找到文件夹,请手动选取");
                            return false;
                        }
                        ArrayList<String> arrayList = new ArrayList<>();
                        for (File file : fileList_QQ) {
                            String path = file.getPath();
                            int index = path.lastIndexOf("/") + 1;
                            String name = path.substring(index, path.length());
                            arrayList.add(name);
                        }
                        PopwindowUtil.popChoice_JG_file(OldBjActivity.this, layoutMainView, arrayList, handler, 4);
                    } else if (valueOf1.endsWith("0")) {//微信
                        if (fileList_WX.isEmpty()) {
                            ToastShow.showShort(OldBjActivity.this, "没有自动找到文件夹,请手动选取");
                            return false;
                        }
                        ArrayList<String> arrayList = new ArrayList<>();
                        for (File file : fileList_WX) {
                            String path = file.getPath();
                            int index = path.lastIndexOf("/") + 1;
                            String name = path.substring(index, path.length());
                            arrayList.add(name);
                        }
                        PopwindowUtil.popChoice_JG_file(OldBjActivity.this, layoutMainView, arrayList, handler, 5);
                    }
                    break;
                case 4://选择了QQ文件
                    String valueOf4 = String.valueOf(msg.obj);
                    File file4 = fileList_QQ.get(Integer.valueOf(valueOf4));
                    dellFile(file4);
                    break;
                case 5://选择了微信文件
                    String valueOf5 = String.valueOf(msg.obj);
                    File file5 = fileList_WX.get(Integer.valueOf(valueOf5));
                    dellFile(file5);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_old_bj);
        dao = new OldBjDao(this);
        initheader();
        initView();
        initData();
    }

    private void initData() {
        detailList.addAll(dao.selectByLimit(MyApp.currProject.getProject_id(), startNum, addNum));
        refreshListView.update();
        if (detailList.size() > 0)
            refreshListView.setCanScroll(true);
        else
            refreshListView.setCanScroll(false);
    }

    void initView() {
        layoutMainView = (LinearLayout) findViewById(R.id.fm_lay_mainView);
        sync_button = (TextView) findViewById(design_continue_button);
        sync_button.setOnClickListener(this);
        findViewById(R.id.m_tv_show_model).setOnClickListener(this);
        findViewById(R.id.design_view).setVisibility(View.GONE);
        findViewById(design_continue_button).setOnClickListener(this);
        findViewById(R.id.m_tv_choosefile).setOnClickListener(this);
        refreshListView = (SwipeRefreshListView) findViewById(R.id.material_srlview);
        refreshListView.setOnRefreshListener(this);
        refreshListView.setFragment(this);
        refreshListView.setAdapter(adapter = new Adapter_OldBj(this, detailList));
    }

    private void initheader() {
        headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(IconSourse.ADD + "",
                View.GONE, R.color.bar_right, ListenerSet.back, "", R.color.title,
                View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));

        String projectName = String.valueOf(MyApp.currProject.getProject_name()).trim();
        if (!projectName.contains("null") || !projectName.isEmpty()) {
            headsecond_layout.setSearchTitle(projectName);
        }
    }

    private List<File> fileList_QQ, fileList_WX;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.m_tv_choosefile:
                importNew();
                break;
            case R.id.design_continue_button:
                for (OldBj l:detailList){
                    l.setProId(MyApp.currProject.getProject_id());
                    l.setGuid(UUID.randomUUID().toString());
                    dao.insert(l);
                }
                ToastUtils.showToast(this,"导入成功");
                findViewById(R.id.design_view).setVisibility(View.GONE);
                break;
            case R.id.m_tv_show_model:
                Intent intent = new Intent(this, ShowBigImageActivity1.class);
                intent.putExtra("bj", 1);
                startActivity(intent);
                break;
        }
    }

    void importNew() {
        if (detailList.size() > 0) {
            ToastShow.showShort(OldBjActivity.this, "您已有表计数据，不能添加新的表计");
            return;
        }
        File skRoot = Environment.getExternalStorageDirectory();
        File[] files = skRoot.listFiles();
        fileList_QQ = new ArrayList<>();
        fileList_WX = new ArrayList<>();
        for (File file : files) {
            if (file.getName().equals("tencent")) {
                for (File file2 : file.listFiles()) {
                    String file2Name = file2.getName();
                    if (file2Name.equals("QQfile_recv")) {
                        for (File file3 : file2.listFiles()) {
                            String name = file3.getName();
                            if (name.endsWith(".xls")) {
                                fileList_QQ.add(file3);
                            }
                        }
                    } else if (file2Name.equals("MicroMsg")) {
                        for (File file4 : file2.listFiles()) {
                            if (file4.getName().equals("Download")) {
                                for (File file5 : file4.listFiles()) {
                                    if (file5.getName().endsWith(".xls")) {
                                        fileList_WX.add(file5);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("微信接收的文件");
        arrayList.add("QQ接收的文件");
        arrayList.add("其他位置文件");
        PopwindowUtil.popChoice_JG_file(this, layoutMainView, arrayList, handler, 3);
    }

    @Override
    public void onRefresh() {
        refreshListView.setRefreshing(false);
    }

    @Override
    public void addMore() {
        super.addMore();
        startNum = addNum;
        addNum += addNum;
        List<OldBj> list = dao.selectByLimit(MyApp.currProject.getProject_id(), startNum, addNum);
        if (list.size() == 0) {
            refreshListView.setCanScroll(false);
        }
        detailList.addAll(list);
        refreshListView.update();
        refreshListView.removeFooterView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode != 2) return;
            Uri uri = data.getData();
            String valueOf = String.valueOf(uri.getPath());
            if (!valueOf.endsWith(".xls")) {
                ToastShow.showShort(OldBjActivity.this, "仅支持97-03 xls格式的Excel");
                return;
            }
            try {
                File file = new File(new URI(uri.toString()));
                dellFile(file);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
    }

    void dellFile(File file) {
        List<OldBj> list = jxlUtil.readBj2DB(file);
        detailList.addAll(list);
        if (detailList.size() > 0) {
            findViewById(R.id.design_view).setVisibility(View.VISIBLE);
        }
        refreshListView.update();
        refreshListView.setCanScroll(false);
    }
}
